import { Form, Modal, Toast } from "@douyinfe/semi-ui";
import { useEffect, useRef, useState } from "react";
import doudian from "../../api/doudian";
import { notificationCatchErr } from "../../lib/utils";


export default function DoudianEditPage({ visible, setVisible, data, setRefreshTable }) {
    const api = useRef();
    useEffect(() => {
        api.current?.setValues(data, true);
    }, [data]);


    const [loading, setLoading] = useState(false);

    const handleOk = () => {
        api.current.validate().then((values) => {
            doudian.save(values).then(({ data, msg }) => {
                Toast.success(msg)
                setRefreshTable()
                setVisible(false);
            }).catch(e => {
                notificationCatchErr("保存失败")(e)
            })
        }).catch((errors) => { console.log(errors); });
    };
    const handleCancel = () => {
        setVisible(false);
    };

    return <>
        <Modal
            title={data === null ? '创建店铺' : '修改店铺'}
            visible={visible}
            width={500}
            loading={loading}
            onOk={handleOk}
            onCancel={handleCancel}
            closeOnEsc={true}
        >
            <Form
                labelPosition={'left'}
                initValues={data}
                labelWidth={110}
                getFormApi={formApi => api.current = formApi}
                render={({ formState, formApi, values }) => (
                    <>
                        <Form.Input
                            field='shop_name'
                            label='店铺名称'
                            placeholder={'请输入您的组织名称'}
                            rules={[
                                { required: true, message: '请填写店铺名称' },
                            ]}
                        />

                        <Form.Input
                            field='cookie'
                            label='登录凭证'
                            placeholder={'登录凭证信息'}
                            rules={[
                                { required: true, message: '请填写登录凭证' },
                            ]}
                        />

                        <Form.Input
                            field='secsdk_csrf_token'
                            label='CSRFTOKEN'
                            placeholder={'请录入CSRFTOKEN'}
                            rules={[
                                { required: true, message: '请填写CSRFTOKEN' },
                            ]}
                        />
                    </>
                )}>
            </Form>

        </Modal>
    </>
}